local Class = require('Core.Class')
local BasePanel = require('Game.UI.Base.BasePanel')
local UIManager = require('Game.Manager.UIManager')
local EventManager = require('Game.Manager.EventManager')
local GameManager = require('Game.Manager.GameManager')

--- @Class LoadingPanel
local LoadingPanel = Class('LoadingPanel', BasePanel)

function LoadingPanel:__init()
    self.MATERIAL_RANGE_ID = CSE.Shader.PropertyToID('_Range')

    self.isEnd = false
    self.isPlayEndAnim = false
    self.animRange = 0.0
    self.LoadingPanelLevelIndexText = nil
    self.LoadingPanelStartAnimMat = nil
end

function LoadingPanel:OnInit()
    BasePanel.OnInit(self)

    self.isEnd = false
    self.isPlayEndAnim = false
    self.animRange = 0.0
    self.LoadingPanelLevelIndexText = self.transform:Find('LevelIndex'):GetComponent('Text')
    self.LoadingPanelStartAnimMat = self.transform:Find('PanelMain'):GetComponent('Image').material
end

function LoadingPanel:OnShow()
    BasePanel.OnShow(self)

    self.isEnd = false
    self.isPlayEndAnim = false
    self.animRange = 0.0
    self:ClearUI()
end

function LoadingPanel:OnHide()
    BasePanel.OnHide(self)

    self.isEnd = false
    self.isPlayEndAnim = false
    self.animRange = 0.0
    self:ClearUI()
end

function LoadingPanel:Update()
    self:LoadingStartAnim()
    self:EndAnim()
end

function LoadingPanel:OnLoaded()
    self.isEnd = true
end

function LoadingPanel:LoadingStartAnim()
    if self.animRange >= 1.0 or self.isEnd then
        return
    end

    self.animRange = self.animRange + CSE.Time.deltaTime
    if self.animRange > 1.0 then
        self.animRange = 1.0
        self.LoadingPanelLevelIndexText.gameObject:SetActive(true)
        self.LoadingPanelLevelIndexText.text = 'Level  1'
    end
    self.LoadingPanelStartAnimMat:SetFloat(self.MATERIAL_RANGE_ID, self.animRange)
end

function LoadingPanel:EndAnim()
    if(not self.isEnd) then
        return
    end

    if not self.isPlayEndAnim then
        if CSE.Input.anyKeyDown then
            -- 开始加载面板结束动画开始
            self.isPlayEndAnim = true
            self:ClearUI()

            -- 触发关卡加载完成事件
            EventManager:Fire('LoadingLevelEnd')
        else
            return
        end
    end

    self.animRange = self.animRange - CSE.Time.deltaTime
    if self.animRange < 0.0 then
        self.animRange = 0.0
        UIManager:HidePanel(self.panelName)
    end
    self.LoadingPanelStartAnimMat:SetFloat(self.MATERIAL_RANGE_ID, self.animRange)
end

function LoadingPanel:ClearUI()
    self.LoadingPanelLevelIndexText.gameObject:SetActive(false)
    self.LoadingPanelLevelIndexText.text = ''
end

return LoadingPanel